<?php
namespace app\model\admin;

use app\model\BaseModel;
use think\facade\Db;

/**
 * 用户模型
 * 对应数据库表: oa_admin (员工表)
 */
class User extends BaseModel
{
    // 设置表名（不包含前缀）
    protected $name = 'admin';
    
    // 设置主键
    protected $pk = 'id';
    
    // 设置字段类型
    protected $type = [
        'status' => 'integer',
        'sex' => 'integer',
        'type' => 'integer',
        'user_type' => 'integer',
        'create_time' => 'integer',
        'update_time' => 'integer',
        'entry_time' => 'integer',
        'birthday' => 'integer',
        'work_date' => 'integer',
        'last_login_time' => 'integer'
    ];

    // 可搜索字段
    protected $searchField = [
        'name',
        'username',
        'mobile',
        'email',
        'status'
    ];

    /**
     * 关联权限组
     */
    public function group()
    {
        return $this->belongsTo(AdminGroup::class, 'group_id', 'id');
    }

    /**
     * 关联部门
     */
    public function department()
    {
        return $this->belongsTo(Department::class, 'did', 'id');
    }

    /**
     * 关联职位
     */
    public function position()
    {
        return $this->belongsTo(Position::class, 'position_id', 'id');
    }

    /**
     * 关联律师信息
     */
    public function lawyer()
    {
        return $this->belongsTo(\app\model\lawyer\Lawyer::class, 'lawyer_id', 'id');
    }

    // 搜索器
    public function searchNameAttr($query, $value)
    {
        $query->where('name', 'like', '%'.$value.'%');
    }

    public function searchUsernameAttr($query, $value)
    {
        $query->where('username', 'like', '%'.$value.'%');
    }

    public function searchMobileAttr($query, $value)
    {
        $query->where('mobile', 'like', '%'.$value.'%');
    }

    public function searchStatusAttr($query, $value)
    {
        $query->where('status', $value);
    }

    public function searchEmailAttr($query, $value)
    {
        $query->where('email', 'like', '%'.$value.'%');
    }

    /**
     * 密码修改器
     */
    public function setPasswordAttr($value, $salt = null)
    {
        // 如果提供了salt参数，则使用它，否则使用 getAttr 方法安全获取 salt 字段值
        if ($salt === null) {
            $salt = $this->getAttr('salt') ?: get_salt(20);
        }
        // 使用 setAttr 方法安全设置 salt 字段值
        $this->setAttr('salt', $salt);
        return md5(md5($value . $salt) . $salt);
    }

    /**
     * 验证密码
     */
    public function verifyPassword($password)
    {
        // 使用 getAttr 方法安全获取 salt 和 pwd 字段值
        $salt = $this->getAttr('salt');
        $pwd = $this->getAttr('pwd');
        return md5(md5($password . $salt) . $salt) === $pwd;
    }
    
    /**
     * 头像获取器
     */
    public function getAvatarAttr($value)
    {
        return $value ?: '/static/admin/images/avatar.png';
    }
    
    /**
     * 密码获取器
     */
    public function getPwdAttr()
    {
        return $this->getData('pwd');
    }

    /**
     * 获取用户列表
     * @param array $params 查询参数
     * @param int $page 页码
     * @param int $limit 每页数量
     * @return array
     */
    public function getList(array $params = [], ?int $page = null, ?int $limit = null): array
    {
        // 使用别名来避免字段名冲突
        $query = $this->newQuery()->alias('u');
        
        // 左连接岗位表以获取岗位名称
        $query->leftJoin('oa_position p', 'u.position_id = p.id');
        
        // 处理搜索条件
        // 优先处理keywords参数，支持多字段搜索
        if (!empty($params['keywords'])) {
            $keyword = '%' . trim($params['keywords']) . '%';
            $query->where(function($where) use ($keyword) {
                $where->where('u.name', 'like', $keyword)
                      ->whereOr('u.username', 'like', $keyword)
                      ->whereOr('u.mobile', 'like', $keyword);
            });
        } else {
            // 如果没有keywords参数，则处理单独的搜索字段
            if (!empty($params['name'])) {
                $query->where('u.name', 'like', '%' . $params['name'] . '%');
            }
            
            if (!empty($params['username'])) {
                $query->where('u.username', 'like', '%' . $params['username'] . '%');
            }
            
            if (!empty($params['mobile'])) {
                $query->where('u.mobile', 'like', '%' . $params['mobile'] . '%');
            }
        }
        
        if (isset($params['status']) && $params['status'] !== '') {
            $query->where('u.status', $params['status']);
        }
        
        // 修复：添加部门筛选条件
        if (isset($params['did']) && $params['did'] !== '' && $params['did'] !== null) {
            $query->where('u.did', $params['did']);
        }
        
        // 获取总数
        $total = $query->count();
        
        // 获取分页数据，包含岗位名称
        $list = $query->page($page, $limit)
            ->field('u.*, p.title as position_name')  // 明确指定要查询的字段，包括岗位名称
            ->order('u.id', 'desc')
            ->select();
            
        return [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ];
    }

    /**
     * 根据ID获取用户信息
     * @param int $id 用户ID
     * @return User|null
     */
    public function getInfoById(int $id)
    {
        return $this->find($id);
    }

    /**
     * 根据用户名获取用户信息
     * @param string $username 用户名
     * @return User|null
     */
    public function getInfoByUsername(string $username)
    {
        return $this->where('username', $username)->find();
    }

    /**
     * 检查用户名是否存在
     * @param string $username 用户名
     * @param int $excludeId 排除的用户ID
     * @return bool
     */
    public function checkUsernameExists(string $username, int $excludeId = 0)
    {
        $query = $this->where('username', $username);
        if ($excludeId > 0) {
            $query->where('id', '<>', $excludeId);
        }
        return $query->count() > 0;
    }

    /**
     * 创建用户
     * @param array $data 用户数据
     * @return int|false
     */
    public function createUserInfo(array $data)
    {
        // 自动生成用户名
        if (empty($data['username'])) {
            $data['username'] = $this->generateUsername($data['name']);
        }
        
        // 生成默认密码
        if (empty($data['reg_pwd'])) {
            // 生成初始密码
            $initialPassword = generate_initial_password(6);
            // 生成 salt
            $salt = get_salt(20);
            $data['salt'] = $salt;
            // 使用 setPasswordAttr 修改器处理密码
            $data['pwd'] = $this->setPasswordAttr($initialPassword, $salt);
            // 保存原始密码到reg_pwd字段
            $data['reg_pwd'] = $initialPassword;
        } else {
            // 如果提供了密码，也生成 salt 并处理密码
            $salt = get_salt(20);
            $data['salt'] = $salt;
            // 使用 setPasswordAttr 修改器处理密码
            $data['pwd'] = $this->setPasswordAttr($data['reg_pwd'], $salt);
            // reg_pwd字段已经包含原始密码，无需再次设置
        }
        
        // 生成默认头像
        if (empty($data['thumb'])) {
            $data['thumb'] = $this->generateAvatar($data['name']);
        }
        
        // 设置创建时间
        $data['create_time'] = time();
        $data['update_time'] = time();
        
        return $this->insertGetId($data);
    }

    /**
     * 更新用户信息
     * @param int $id 用户ID
     * @param array $data 用户数据
     * @return bool
     */
    public function updateUserInfo(int $id, array $data)
    {
        $data['update_time'] = time();
        
        // 如果提供了password字段，则生成新的 salt 并处理密码
        if (isset($data['password']) && !empty($data['password'])) {
            $salt = get_salt(20);
            $data['salt'] = $salt;
            // 使用 setPasswordAttr 修改器处理密码，传递salt参数
            $data['pwd'] = $this->setPasswordAttr($data['password'], $salt);
            // 保存原始密码
            $data['reg_pwd'] = $data['password'];
            // 移除password字段，避免重复存储
            unset($data['password']);
        }
        // 兼容旧的pwd字段处理方式
        elseif (isset($data['pwd']) && !empty($data['pwd'])) {
            $salt = get_salt(20);
            $data['salt'] = $salt;
            // 保存原始密码
            $data['reg_pwd'] = $data['pwd'];
            // 使用 setPasswordAttr 修改器处理密码，传递salt参数
            $data['pwd'] = $this->setPasswordAttr($data['pwd'], $salt);
        }
        
        $result = $this->where('id', $id)->update($data);
        return $result !== false;
    }

    /**
     * 删除用户（软删除）
     * @param int $id 用户ID
     * @return bool
     */
    public function deleteUserInfo(int $id)
    {
        return $this->destroy($id);
    }

    /**
     * 删除用户（别名方法，用于兼容控制器调用）
     * @param int $id 用户ID
     * @return bool
     */
    public function deleteUser(int $id)
    {
        return $this->deleteUserInfo($id);
    }

    /**
     * 生成用户名
     * @param string $name 中文姓名
     * @return string 生成的用户名
     */
    private function generateUsername($name)
    {
        // 确保姓名不为空
        if (empty($name)) {
            $name = 'user' . time();
        }
        
        // 将姓名转换为拼音
        $username = $this->nameToPinyin($name);
        
        // 如果转换后仍为空，则使用姓名+随机数
        if (empty($username)) {
            $username = $name . rand(1000, 9999);
        }
        
        // 检查用户名是否已存在，如果存在则添加数字后缀
        $baseUsername = $username;
        $suffix = 1;
        while ($this->checkUsernameExists($username)) {
            $username = $baseUsername . $suffix;
            $suffix++;
        }
        
        return $username;
    }

    /**
     * 将中文字符转换为拼音（简化版）
     * @param string $name 中文姓名
     * @return string 拼音
     */
    private function nameToPinyin($name)
    {
        // 常见汉字拼音映射表（已修复重复键问题）
        $pinyinMap = [
            '张' => 'zhang', '李' => 'li', '王' => 'wang', '刘' => 'liu', '陈' => 'chen',
            '杨' => 'yang', '赵' => 'zhao', '黄' => 'huang', '周' => 'zhou', '吴' => 'wu',
            '徐' => 'xu', '孙' => 'sun', '胡' => 'hu', '朱' => 'zhu', '高' => 'gao',
            '林' => 'lin', '何' => 'he', '郭' => 'guo', '马' => 'ma', '罗' => 'luo',
            '梁' => 'liang', '宋' => 'song', '郑' => 'zheng', '谢' => 'xie', '韩' => 'han',
            '唐' => 'tang', '冯' => 'feng', '于' => 'yu', '董' => 'dong', '萧' => 'xiao',
            '程' => 'cheng', '曹' => 'cao', '袁' => 'yuan', '邓' => 'deng', '许' => 'xu',
            '傅' => 'fu', '沈' => 'shen', '曾' => 'zeng', '彭' => 'peng', '吕' => 'lv',
            '苏' => 'su', '卢' => 'lu', '蒋' => 'jiang', '蔡' => 'cai', '贾' => 'jia',
            '丁' => 'ding', '魏' => 'wei', '薛' => 'xue', '叶' => 'ye', '阎' => 'yan',
            '余' => 'yu', '潘' => 'pan', '杜' => 'du', '戴' => 'dai', '夏' => 'xia',
            '钟' => 'zhong', '汪' => 'wang', '田' => 'tian', '任' => 'ren', '姜' => 'jiang',
            '范' => 'fan', '方' => 'fang', '石' => 'shi', '姚' => 'yao', '谭' => 'tan',
            '廖' => 'liao', '邹' => 'zou', '熊' => 'xiong', '金' => 'jin', '陆' => 'lu',
            '郝' => 'hao', '孔' => 'kong', '白' => 'bai', '崔' => 'cui', '康' => 'kang',
            '毛' => 'mao', '邱' => 'qiu', '秦' => 'qin', '江' => 'jiang', '史' => 'shi',
            '顾' => 'gu', '侯' => 'hou', '邵' => 'shao', '孟' => 'meng', '龙' => 'long',
            '万' => 'wan', '段' => 'duan', '雷' => 'lei', '钱' => 'qian', '汤' => 'tang',
            '尹' => 'yin', '黎' => 'li', '易' => 'yi', '常' => 'chang', '武' => 'wu',
            '乔' => 'qiao', '贺' => 'he', '赖' => 'lai', '龚' => 'gong', '文' => 'wen',
            '庞' => 'pang', '樊' => 'fan', '兰' => 'lan', '殷' => 'yin', '施' => 'shi',
            '陶' => 'tao', '翟' => 'zhai', '安' => 'an', '颜' => 'yan', '倪' => 'ni',
            '严' => 'yan', '牛' => 'niu', '温' => 'wen', '芦' => 'lu', '季' => 'ji',
            '俞' => 'yu', '章' => 'zhang', '鲁' => 'lu', '韦' => 'wei', '昌' => 'chang',
            '苗' => 'miao', '凤' => 'feng', '花' => 'hua', '柳' => 'liu', '柏' => 'bai',
            '伍' => 'wu', '齐' => 'qi', '鲍' => 'bao', '费' => 'fei', '廉' => 'lian',
            '岑' => 'cen', '滕' => 'teng', '毕' => 'bi', '邬' => 'wu', '乐' => 'le',
            '谌' => 'chen', '解' => 'xie', '应' => 'ying', '宗' => 'zong', '宣' => 'xuan',
            '贲' => 'ben', '郁' => 'yu', '单' => 'shan', '杭' => 'hang', '洪' => 'hong',
            '包' => 'bao', '诸' => 'zhu', '左' => 'zuo', '吉' => 'ji', '钮' => 'niu',
            '嵇' => 'ji', '邢' => 'xing', '滑' => 'hua', '裴' => 'pei', '荣' => 'rong',
            '翁' => 'weng', '荀' => 'xun', '羊' => 'yang', '於' => 'yu', '惠' => 'hui',
            '甄' => 'zhen', '曲' => 'qu', '封' => 'feng', '芮' => 'rui', '羿' => 'yi',
            '储' => 'chu', '靳' => 'jin', '汲' => 'ji', '邴' => 'bing', '糜' => 'mi',
            '松' => 'song', '井' => 'jing', '富' => 'fu', '巫' => 'wu', '乌' => 'wu',
            '焦' => 'jiao', '巴' => 'ba', '弓' => 'gong', '牧' => 'mu', '隗' => 'kui',
            '山' => 'shan', '谷' => 'gu', '车' => 'che', '宓' => 'mi', '蓬' => 'peng',
            '全' => 'quan', '郗' => 'xi', '班' => 'ban', '仰' => 'yang', '秋' => 'qiu',
            '仲' => 'zhong', '伊' => 'yi', '宫' => 'gong', '宁' => 'ning', '仇' => 'qiu',
            '栾' => 'luan', '暴' => 'bao', '甘' => 'gan', '钭' => 'tou', '厉' => 'li',
            '戎' => 'rong', '祖' => 'zu', '符' => 'fu', '景' => 'jing', '詹' => 'zhan',
            '束' => 'shu', '幸' => 'xing', '司' => 'si', '韶' => 'shao', '郜' => 'gao',
            '蓟' => 'ji', '薄' => 'bo', '印' => 'yin', '宿' => 'su', '怀' => 'huai',
            '蒲' => 'pu', '邰' => 'tai', '从' => 'cong', '鄂' => 'e', '索' => 'suo',
            '咸' => 'xian', '籍' => 'ji', '卓' => 'zhuo', '蔺' => 'lin', '屠' => 'tu',
            '蒙' => 'meng', '池' => 'chi', '阴' => 'yin', '胥' => 'xu', '能' => 'nai',
            '苍' => 'cang', '双' => 'shuang', '闻' => 'wen', '莘' => 'shen', '党' => 'dang',
            '贡' => 'gong', '劳' => 'lao', '逄' => 'pang', '姬' => 'ji', '申' => 'shen',
            '扶' => 'fu', '堵' => 'du', '冉' => 'ran', '宰' => 'zai', '雍' => 'yong',
            '郤' => 'xi', '璩' => 'qu', '桑' => 'sang', '桂' => 'gui', '濮' => 'pu',
            '寿' => 'shou', '通' => 'tong', '边' => 'bian', '扈' => 'hu', '燕' => 'yan',
            '冀' => 'ji', '郏' => 'jia', '浦' => 'pu', '尚' => 'shang', '农' => 'nong',
            '别' => 'bie', '庄' => 'zhuang', '晏' => 'yan', '柴' => 'chai', '瞿' => 'qu',
            '充' => 'chong', '慕' => 'mu', '连' => 'lian', '茹' => 'ru', '习' => 'xi',
            '宦' => 'huan', '艾' => 'ai', '鱼' => 'yu', '容' => 'rong', '向' => 'xiang',
            '古' => 'gu', '慎' => 'shen', '戈' => 'ge', '庾' => 'yu', '终' => 'zhong',
            '暨' => 'ji', '居' => 'ju', '衡' => 'heng', '步' => 'bu', '都' => 'du',
            '耿' => 'geng', '满' => 'man', '弘' => 'hong', '匡' => 'kuang', '国' => 'guo',
            '寇' => 'kou', '广' => 'guang', '禄' => 'lu', '阙' => 'que', '东' => 'dong',
            '欧' => 'ou', '殳' => 'shu', '沃' => 'wo', '利' => 'li', '蔚' => 'wei',
            '越' => 'yue', '夔' => 'kui', '隆' => 'long', '师' => 'shi', '巩' => 'gong',
            '厍' => 'she', '聂' => 'nie', '晁' => 'chao', '勾' => 'gou', '敖' => 'ao',
            '融' => 'rong', '冷' => 'leng', '訾' => 'zi', '辛' => 'xin', '阚' => 'kan',
            '那' => 'na', '简' => 'jian', '饶' => 'rao', '空' => 'kong', '毋' => 'wu',
            '沙' => 'sha', '乜' => 'nie', '养' => 'yang', '鞠' => 'ju', '须' => 'xu',
            '丰' => 'feng', '巢' => 'chao', '关' => 'guan', '蒯' => 'kuai', '相' => 'xiang',
            '查' => 'cha', '后' => 'hou', '荆' => 'jing', '红' => 'hong', '游' => 'you',
            '竺' => 'zhu', '权' => 'quan', '逯' => 'lu', '盖' => 'ge', '益' => 'yi',
            '桓' => 'huan', '公' => 'gong', '万俟' => 'moqi', '司马' => 'sima',
            '上官' => 'shangguan', '欧阳' => 'ouyang', '夏侯' => 'xiahou', '诸葛' => 'zhuge',
            '闻人' => 'wenren', '东方' => 'dongfang', '赫连' => 'helian', '皇甫' => 'huangfu',
            '尉迟' => 'yuchi', '公羊' => 'gongyang', '澹台' => 'tantai', '公冶' => 'gongye',
            '宗政' => 'zongzheng', '濮阳' => 'puyang', '淳于' => 'chunyu', '单于' => 'chanyu',
            '太叔' => 'taishu', '申屠' => 'shentu', '公孙' => 'gongsun', '仲孙' => 'zhongsun',
            '轩辕' => 'xuanyuan', '令狐' => 'linghu', '钟离' => 'zhongli', '宇文' => 'yuwen',
            '长孙' => 'zhangsun', '慕容' => 'murong', '鲜于' => 'xianyu', '闾丘' => 'lvqiu',
            '司徒' => 'situ', '司空' => 'sikong', '亓官' => 'qiguan', '司寇' => 'sikou',
            '仉' => 'zhang', '督' => 'du', '子车' => 'ziju', '颛孙' => 'zhuansun', '端木' => 'duanmu',
            '巫马' => 'wuma', '公西' => 'gongxi', '漆雕' => 'qidiao', '乐正' => 'yuezheng',
            '壤驷' => 'rangsi', '公良' => 'gongliang', '拓跋' => 'tuoba', '夹谷' => 'jiagu',
            '宰父' => 'zaifu', '谷梁' => 'guliang', '晋' => 'jin', '楚' => 'chu', '闫' => 'yan',
            '法' => 'fa', '汝' => 'ru', '鄢' => 'yan', '涂' => 'tu', '钦' => 'qin',
            '干' => 'gan', '百里' => 'baili', '东郭' => 'dongguo', '南门' => 'nanmen', '呼延' => 'huyan',
            '归' => 'gui', '海' => 'hai', '羊舌' => 'yangshe', '微生' => 'weisheng', '岳' => 'yue',
            '帅' => 'shuai', '缑' => 'gou', '亢' => 'kang', '况' => 'kuang', '有' => 'you',
            '琴' => 'qin', '商' => 'shang', '牟' => 'mou', '佘' => 'she', '佴' => 'nai',
            '伯' => 'bo', '赏' => 'shang', '南宫' => 'nangong', '墨' => 'mo', '哈' => 'ha',
            '谯' => 'qiao', '笪' => 'da', '年' => 'nian', '爱' => 'ai', '阳' => 'yang',
            '佟' => 'tong', '第五' => 'diwu', '言' => 'yan', '福' => 'fu'
        ];
        
        $pinyin = '';
        $nameLength = mb_strlen($name, 'UTF-8');
        
        // 处理复姓
        if ($nameLength >= 2) {
            $firstTwoChars = mb_substr($name, 0, 2, 'UTF-8');
            if (isset($pinyinMap[$firstTwoChars])) {
                $pinyin .= $pinyinMap[$firstTwoChars];
                $name = mb_substr($name, 2, null, 'UTF-8');
                $nameLength -= 2;
            }
        }
        
        // 处理单字姓氏和名字
        for ($i = 0; $i < $nameLength; $i++) {
            $char = mb_substr($name, $i, 1, 'UTF-8');
            if (isset($pinyinMap[$char])) {
                $pinyin .= $pinyinMap[$char];
            } else {
                // 如果找不到映射，使用字符本身（可能是英文或其他字符）
                $pinyin .= $char;
            }
        }
        
        // 移除空格和特殊字符，只保留字母和数字
        $pinyin = preg_replace('/[^a-zA-Z0-9]/', '', $pinyin);
        
        // 转换为小写
        $pinyin = strtolower($pinyin);
        
        return $pinyin;
    }

    /**
     * 生成默认头像URL
     * @param string $name 用户姓名
     * @return string 头像URL
     */
    private function generateAvatar($name)
    {
        $avatarChar = mb_substr($name, 0, 1, 'UTF-8');
        $avatarBgColors = ['#3498db', '#2ecc71', '#e74c3c', '#f39c12', '#9b59b6', '#1abc9c', '#34495e'];
        $bgColor = $avatarBgColors[ord($avatarChar) % count($avatarBgColors)];
        return "https://ui-avatars.com/api/?name=" . urlencode($avatarChar) . "&background=" . str_replace('#', '', $bgColor) . "&color=ffffff";
    }
}